<?php
	class InstallerController extends AppController
	{
		var $uses = array();
		function beforeFilter()
		{
			App::import("Vendor","Installer.Installer");
			callHooks('setIntallerSteps','.+',$this);
			parent::beforeFilter();
		}
		function install($step = 1)
		{
			$this->layout = "installer";
			$StepObject = Installer::getStepByNo($step);
			$this->Set("step",$step);
			if(!$StepObject)
			{
				die("error in installation");
			}
			//url will be used for 
			//url should be cakephp url array
			if($StepObject->url)
			{
				$StepObject->url['step'] = $step; 
				$this->redirect($StepObject->url);
			}
			$Model = null;
			if($StepObject->model)
			{
				$Model = cri($StepObject->model);
			}
			if($Model && $this->data)
			{
				$Model->create();
				$save = true;
				if($StepObject->validateFirst)
				{
					$Model->set($this->data);
					$save = $Model->validates();
				}
				if($save && $Model->save($this->data))
				{
					$this->goToNext($step);
				}
			}
			$this->set("Model",$Model);
			$this->set("StepObject",$StepObject);
			$this->helpers[] = 'Form';
			if($StepObject->view_file)
			{
				$this->render($StepObject->view_file);
			}
		}
		
		function goToNext($step)
		{
			$next = $step+1;
			$NextStepObject = Installer::getStepByNo($next);
			if(is_object($NextStepObject))
			{
				$this->redirect(array('action'=>"install",$next));
			}else
			{
				if(count(Installer::getSteps()) == $step)
				{
					Installer::setAsInstalled($this);
					$this->successMsg(__("Installation completed."));
				}
			}
			$this->redirect("/");
		}
		
		protected function getSteps()
		{
			App::import("Vendor","Installer.Installer");
			$step = new InstallerStep(array("view_file"=>"welcome"));
			Installer::addStep($step,"intro");
			$step = new InstallerStep(array("model"=>"Config.DatabaseConfig","fieldGroup"=>"setup",'validateFirst'=> true));
			Installer::addStep($step,"db_config");
			$step = new InstallerStep(array("model"=>"Backend.BackendConfig","fieldGroup"=>"setup",'validateFirst'=> true));
			Installer::addStep($step,"backend_config");
		}
		
		protected function getStepInfo($step)
		{
			$stepInfo = false;
			$steps = $this->getSteps();
			if(isset($steps[$step]))
			{
				$defaultInfo = array("title"=>null,'model'=>null,'fieldGroup'=>null,'view_file'=>null,'url'=>null);
				$stepInfo = $steps[$step];
				$stepInfo = am($defaultInfo,$stepInfo);
			}
			return $stepInfo;
		}
		
		function goToNextStep($step)
		{
			
		}
	}
?>